package com.creditease.shield.flow.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.creditease.shield.flow.common.msg.Request;
import com.creditease.shield.flow.common.msg.Response;
import com.creditease.shield.flow.exception.ServerException;
import com.creditease.shield.flow.service.CounterService;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Handles both client-side and server-side handler depending on which
 * constructor was called.
 */
@Component
@Sharable
public class FlowNoServerHandler extends SimpleChannelInboundHandler<Request> implements ApplicationContextAware{
	private static final Logger logger = LoggerFactory.getLogger(FlowNoServerHandler.class);
	@Autowired
	private CounterService counterService;
	
	public FlowNoServerHandler(){
		
	}
	
    @Override
	protected void channelRead0(ChannelHandlerContext ctx, Request msg) throws Exception {
    	 
         if("0".equals(msg.getRequestType())){
        	 System.out.println("heart beat");
         }else{
        	 Response response = new Response();
             response.setTraceId(msg.getTraceId());
        	 try {
                 logger.info("server handle request:{}",msg);
                 response = handle(msg);
             } catch (Throwable t) {
                 logger.error(t.getMessage(),t);
                 response.setTraceId(msg.getTraceId());
                 response.setErrorMessage(t.getMessage());
             }
             ctx.writeAndFlush(response);
         }
	}
    
    private Response handle(Request request) throws Throwable {
    	 //counterService=(CounterService)this.applicationContext.getBean("counterService");
         String flowNo=counterService.getFlowNo(request.getKeyName());
         Response response=new Response();
         response.setTraceId(request.getTraceId());
         response.setFlowNo(flowNo);
         return response;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error(cause.getMessage(), cause);
        Response response = new Response();
        if(cause instanceof ServerException){
            response.setTraceId(((ServerException) cause).getTraceId());
        }
        response.setErrorMessage(cause.getMessage());
        ctx.writeAndFlush(response);
    }
    
    
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		
	}
    
    

}
